<?php

namespace App\Console\Commands\User;

use App\Console\Commands\OpenShop\RefreshProvinceDevelopers;
use App\Console\Commands\OpenShop\RefreshSolicitBusiness;
use App\Enums\Common\NsqEnum;
use App\Models\Kms\Fs\FsDepartmentsModel;
use App\Models\Kms\User\KmsUser;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageUserModel;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Log;
use Kuafu\Nsq\NsqSubscriber;
use NSQClient\Message\Message;

class SubFsUserAddCommand extends Command
{
    protected $signature = 'nsq:sub-fs-user-add';

    protected $description = '订阅fs-user新增事件';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        (new NsqSubscriber(config('nsq.default.address')))
            ->sub(NsqEnum::TOPIC_FS_USER_NEW, NsqEnum::CHANNEL_TIGER_FS_USER_NEW, function (Message $message) {
                try {
                    $data = $message->data();

                    //飞书新增用户 - 同步区域开发经理
                    self::synchronizeOrganization($data);

                    $this->do();

                    $message->done();
                } catch (\Exception $exception) {
                    logException("飞书新增用户nsq消费异常", $exception, null, true, true);
                }
            });
    }

    private function do()
    {
        // 刷新省区开发
        Artisan::call('openShop:refresh-province-developers');
        //(new RefreshProvinceDevelopers())->doHandle();

        // 刷新招商人员
        (new RefreshSolicitBusiness())->doHandle();
    }

    /**
     * 飞书新增用户 - 同步区域开发经理
     *
     * @param array $data
     */
    public static function synchronizeOrganization(array $data)
    {
        Log::info("飞书新增用户 - 同步区域开发经理", $data);
        try {
            //获取分公司部门树状结构数据
            $organizationUserTree = collect(FsDepartmentsModel::departmentUserTree())->where("name", "分公司")->first();

            Log::info("飞书新增用户 - 同步区域开发经理" . collect($data["users"])->pluck("userId")->except("."), $data);
            $newOrganizationUser = [];
            KmsUser::query()
                   ->whereIn("userId", collect($data["users"])->pluck("userId")->toArray())
                   ->where("isExited", 0)
                   ->where("isResigned", 0)
                   ->where("jobTitle", '区域开发经理')
                   ->get()
                   ->each(function (KmsUser $kmsUser) use ($organizationUserTree, &$newOrganizationUser) {
                       $exists                = false;
                       $existsTopOrganization = null;
                       collect(attributeGet($organizationUserTree, "child", []))->each(function ($topChild) use (
                           $kmsUser,
                           &$exists,
                           &$existsTopOrganization,
                           &$newOrganizationUser
                       ) {
                           if (!empty($topChild["child"])) {
                               collect($topChild["child"])->each(function ($lastChild) use ($kmsUser, &$exists) {
                                   if (
                                       !empty($lastChild["user_rel"])
                                       &&
                                       collect($lastChild["user_rel"])->where("userId", $kmsUser->userId)->first()
                                   ) {
                                       $exists = true;
                                       return false;
                                   }
                               });
                               if ($exists) {
                                   $existsTopOrganization = $topChild;
                                   return false;
                               }
                           }
                       });

                       if ($existsTopOrganization) {
                           $organizationName        = collect($existsTopOrganization)->only(["name"])->toArray();
                           $organizationManageModel = OpenShopOrganizationManageModel::query()
                                                                                     ->where("name", "like",
                                                                                         "%{$organizationName["name"]}%")
                                                                                     ->first();
                           if ($organizationManageModel) {
                               array_push($newOrganizationUser, [
                                   'manageId'     => $organizationManageModel->id,
                                   'name'         => vsprintf("%s(%s)", [
                                       attributeGet($kmsUser, "name", ""),
                                       attributeGet($kmsUser, "nickname", ""),
                                   ]),
                                   'type'         => OpenShopOrganizationManageUserModel::TYPE_SITE_SELECTION_DEVELOPMENT,
                                   'userId'       => attributeGet($kmsUser, "rmsUserId", 0),
                                   'createdByUid' => 0,
                                   'updatedByUid' => 0,
                                   "createdAt"    => time(),
                                   "updatedAt"    => time()
                               ]);
                           }

                       }
                   });

            if (!empty($newOrganizationUser)) {
                OpenShopOrganizationManageUserModel::query()->insert($newOrganizationUser);
            }
        } catch (\Exception $exception) {
            logException("飞书新增用户 - 同步区域开发经理 失败", $exception, $data, true, true);
        }
    }
}
